package com.iflytek.autofly.setting.biz.system;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.SystemProperties;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.iflytek.autofly.bluetoothservice.aidl.RRBluetoothDevice;
import com.iflytek.autofly.bluetoothservice.util.BluetoothManager;
import com.iflytek.autofly.bluetoothservice.util.BluetoothServiceCons;
import com.iflytek.autofly.bluetoothservice.util.IBluetoothSettingListener;
import com.iflytek.autofly.navisetting.NaviSetting;
import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.util.SpUtil;
import com.iflytek.autofly.utils.FlyLog;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <b>Description: </b>关于系统<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015/12/7</td>
 * <td>10:41</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public class AboutSystem {
    private static final String TAG = "AboutSystem";
    private static final String TYPR_PROPERTY = "ro.product.model";
    private static final java.lang.String SN_PROPERTY = "persist.sys.navi.uuid";
    private static final java.lang.String FLY_VERSION_PROPERTY = "ro.autofly.vn";
    private static final java.lang.String ANDROID_VERSION_PROPERTY = "ro.build.version.release";
    private static final java.lang.String PLATFORM_VERSION_PROPERTY = "ro.build.id";
    private static final java.lang.String HARDWARE_VERSION_PROPERTY = "persist.sys.product.board";
    private static final java.lang.String MCU_VERSION_PROPERTY = "persist.sys.navi.mcu_version";
    private static final java.lang.String UBOOT_VERSION_FILE = "/device/bootversion.txt";
    private String type;
    private String softwareVersion;
    private String sn;
    private String imei;
    private String mac;
    private String ip;
    private String btAddr;
    private String number;
    private String androidVersion;
    private AtomicBoolean isInited;
    private String platformVersion;
    private NaviSetting mNaviSetting;
    private AtomicInteger mNaviServiceReady = new AtomicInteger(0);
    private AtomicInteger mBtServiceReady = new AtomicInteger(0);
    private Context mContext;
    private OnNaviInfoListener mOnNaviInfoListener;
    private String hardwareVersion;
    private String mcuVersion;
    private OnBluetoothInfoListener mOnBluetoothInfoListener;
    private BluetoothManager mBtMngr;
    private String imsi;
    private String ubootVersion = "";


    private AboutSystem() {
        isInited = new AtomicBoolean(false);
    }

    public static AboutSystem getInstance() {
        return AboutSystemInst.INST;
    }

    public boolean isInited() {
        return isInited.get();
    }

    public void init(Context context) {
        if (isInited()) {
            return;
        }
        mContext = context;

        FileInputStream ubootFile = null;
        try {
            ubootFile = new FileInputStream(UBOOT_VERSION_FILE);
            byte[] version = new byte[1024];
            if (ubootFile.read(version, 0, 1024) > 0) {
                ubootVersion = new String(version);
                int start = ubootVersion.indexOf("(");
                int end = ubootVersion.indexOf(")");
                ubootVersion = ubootVersion.substring(start + 1, end);
            }
        } catch (Exception e) {
            FlyLog.e(TAG, e);
        } finally {
            if (ubootFile != null) {
                try {
                    ubootFile.close();
                } catch (IOException e) {
                    FlyLog.w(TAG, e);
                }
            }
        }

        type = SystemProperties.get(TYPR_PROPERTY);
        sn = SystemProperties.get(SN_PROPERTY);
        softwareVersion = SystemProperties.get(FLY_VERSION_PROPERTY);
        platformVersion = SystemProperties.get(PLATFORM_VERSION_PROPERTY);
        androidVersion = SystemProperties.get(ANDROID_VERSION_PROPERTY);
        hardwareVersion = SystemProperties.get(HARDWARE_VERSION_PROPERTY);
        mcuVersion = SystemProperties.get(MCU_VERSION_PROPERTY);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (info != null) {
            int ipAddr = info.getIpAddress();
            ip = (ipAddr & 0xFF) + "."
                    + ((ipAddr >> 8) & 0xFF) + "."
                    + ((ipAddr >> 16) & 0xFF) + "."
                    + ((ipAddr >> 24) & 0xFF);
            mac = info.getMacAddress();
        } else {
            ip = context.getString(R.string.sys_aboutsys_ip_unknown);
            mac = context.getString(R.string.sys_aboutsys_mac_unknown);
        }

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        imei = tm.getDeviceId();
        number = tm.getLine1Number();
        imsi = tm.getSubscriberId();
        isInited.set(true);


//        <string name="sys.aboutsys.bluetooth_addr">蓝牙地址</string>
//        <string name="sys.aboutsys.contract_info">联系方式</string>
//        <string name="sys.aboutsys.service_term">服务条款</string>
//        <string name="sys.aboutsys.disclaimer">免责声明</string>
    }

    private void updateNaviVersion() {
        FlyLog.d(TAG, "enter");
        if (mNaviServiceReady.incrementAndGet() < 2) {
            return;
        }
        FlyLog.d(TAG, "real get");
        String naviVersion = mNaviSetting.getNaviVersion();
        String naviDataVersion = mNaviSetting.getNaviDataVersion();
        if (mOnNaviInfoListener != null) {
            mOnNaviInfoListener.onNaviInfo(naviVersion, naviDataVersion);
        }
    }

    public String getType() {
        return type;
    }

    public String getSoftwareVersion() {
        return softwareVersion;
    }

    public String getAndroidVersion() {
        return androidVersion;
    }

    public String getSn() {
        return sn;
    }

    public String getImei() {
        return imei;
    }

    public String getMac() {
        if (TextUtils.isEmpty(mac)) {
            return "";
        }
        return mac.toUpperCase();
    }

    public String getIp() {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (info != null) {
            int ipAddr = info.getIpAddress();
            ip = (ipAddr & 0xFF) + "."
                    + ((ipAddr >> 8) & 0xFF) + "."
                    + ((ipAddr >> 16) & 0xFF) + "."
                    + ((ipAddr >> 24) & 0xFF);
        } else {
            ip = mContext.getString(R.string.sys_aboutsys_ip_unknown);
        }
        return ip;
    }

    public void getBtAddr(OnBluetoothInfoListener l) {
        FlyLog.d(TAG, "enter");
        mOnBluetoothInfoListener = l;
        String addr = SpUtil.getString(mContext, "bluetooth", "mac", "");
        if (!TextUtils.isEmpty(addr)) {
            if (l != null) {
                l.onBluetoothInfo(addr);
            }
            return;
        }

        mBtServiceReady.set(0);
        mBtMngr = BluetoothManager.registerListener(mContext, new IBluetoothSettingListener() {
                    @Override
                    public void onDeviceListChanged(List<RRBluetoothDevice> list) {
                    }

                    @Override
                    public void onConnectStatus(RRBluetoothDevice rrBluetoothDevice) {
                    }

                    @Override
                    public void onA2DPConnectStatus(int i) {
                    }

                    @Override
                    public void onServiceStatusChanged(int status) {
                        switch (status) {
                            case BluetoothServiceCons.AidlStatus.SERVICE_AIDL_BOUND:
                                updateBtInfo();
                                break;
                        }
                    }

                    @Override
                    public void onScanStart() {
                    }

                    @Override
                    public void onScanEnd() {
                    }

                    @Override
                    public void onDeviceFound(RRBluetoothDevice rrBluetoothDevice) {
                    }
                },

                BluetoothServiceCons.ClientType.CLIENT_TYPE_SETTING);

        updateBtInfo();
    }

    private void updateBtInfo() {
        FlyLog.d(TAG, "enter");
        if (mBtServiceReady.incrementAndGet() < 2) {
            return;
        }
        FlyLog.d(TAG, "real get");
        String btAddr = mBtMngr.getAddress();
        if (TextUtils.isEmpty(btAddr)) {
            btAddr = "";
        }
        SpUtil.saveString(mContext, "bluetooth", "mac", btAddr);
        if (mOnBluetoothInfoListener != null) {
            mOnBluetoothInfoListener.onBluetoothInfo(btAddr.toUpperCase());
        }
    }

    public String getNumber() {
        return number;
    }

    public void getNaviInfo(OnNaviInfoListener l) {
        FlyLog.d(TAG, "enter");
        mOnNaviInfoListener = l;
        mNaviSetting = NaviSetting.registerListener(mContext, new NaviSetting.IBindListener() {
            @Override
            public void onServiceStatusChanged(NaviSetting.AidlStatus status) {
                FlyLog.d(TAG, "status: " + status);
                if (status == NaviSetting.AidlStatus.SERVICE_AIDL_BOUND) {
                    updateNaviVersion();
                }
            }
        });
        updateNaviVersion();
    }

    public String getHardwareVersion() {
        return hardwareVersion;
    }

    public String getSystemVersion() {
        return platformVersion;
    }

    public String getMcuVersion() {
        return mcuVersion;
    }

    public String getContractInfo() {
        // TODO
        return "hfwang2@iflytek.com";
    }

    public String getImsi() {
        return imsi;
    }

    public String getUbootVersion() {
        return ubootVersion;
    }

    public interface OnNaviInfoListener {
        void onNaviInfo(String app, String data);
    }

    public interface OnBluetoothInfoListener {
        void onBluetoothInfo(String btAddr);
    }

    private static class AboutSystemInst {
        private static AboutSystem INST = new AboutSystem();
    }
}
